﻿using System.Reflection;

namespace System.Xml.Linq
{
	internal static class XElementEnumExtensions
	{
		/// <summary>
		/// Gets the specified attribute as an enum.
		/// </summary>
		/// <typeparam name="TEnum">The type of attribute as enum</typeparam>
		/// <param name="element">The element.</param>
		/// <param name="attributeName">Name of the attribute.</param>
		/// <returns>Attribute as enum of type TEnum</returns>
		public static TEnum AttributeValueAsEnum<TEnum>(this XElement element, XName attributeName)
		{
			EnumReflector.EnsureIsEnum(typeof(TEnum));
			XAttribute attribute = element.Attribute(attributeName);
			if (attribute == null)
			{
				string message = String.Format("The required attribute '{0}' was not found on '{1}'.", attributeName, element.Name);
				throw new XmlException(message);
			}
			return EnumReflector.Parse<TEnum>(attribute.Value);
		}

		/// <summary>
		/// Gets the specified attributes value as an enum, or the default value if the attribute is missing.
		/// </summary>
		/// <typeparam name="TEnum">The type of attribute as enum</typeparam>
		/// <param name="element">The element.</param>
		/// <param name="attributeName">Name of the attribute.</param>
		/// <param name="defaultValue">The default value.</param>
		/// <returns>Attribute as enum of type TEnum</returns>
		public static TEnum AttributeValueAsEnum<TEnum>(this XElement element, XName attributeName, TEnum defaultValue)
		{
			EnumReflector.EnsureIsEnum(typeof(TEnum));
			XAttribute attribute = element.Attribute(attributeName);
			return attribute == null ? defaultValue : EnumReflector.Parse<TEnum>(attribute.Value);
		}
	}
}